package leja.notis;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;

public class SettingsFragment extends PreferenceFragment
        implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_THEME = "pref_theme_key";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);

        /*
        // Set Summaries to show EntryValues instead of Entries

        // Iterate through PreferenceCategories
        for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
            PreferenceCategory pc = (PreferenceCategory)getPreferenceScreen().getPreference(i);

            // Iterate through Preferences inside a PreferenceCategory
            for (int j = 0; j < pc.getPreferenceCount(); j++) {
                Preference p = pc.getPreference(j);

                if (p instanceof ListPreference) {
                    p.setSummary(((ListPreference) p).getValue());
                }
                if (p instanceof EditTextPreference) {
                    p.setSummary(((EditTextPreference) p).getText());
                }
            }
        }
        */
    }

    @Override
    public void onResume() {
        super.onResume();
        // Set up a listener whenever a key changes
        getPreferenceManager().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        // Remove the listener when app loses focus
        getPreferenceManager().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        Preference pref = findPreference(key);
        // Set Summary to EntryValue for all Preferences
        //pref.setSummary(sharedPreferences.getString(key, ""));

        // Change theme immediately
        if (key.equals(KEY_THEME)) {
            ListPreference lp = (ListPreference) pref;
            ThemeChanger.changeToTheme(getActivity(), Integer.valueOf(lp.getValue()));
        }
    }

}
